package com.sline.exception;

public class Demo6_Exception {
    /*  throw和throws的区别
    *   a. throws
    *   用在方法声明后面, 跟的是异常类名
    *   可以跟多个异常类名, 用逗号隔开
    *   表示抛出异常, 由该方法的调用者来处理
    *   b. throw
    *   用在方法体内, 跟的是异常对象
    *   只能抛出一个异常对象
    *   表示抛出异常, 由方法体内的语句处理
     */


    public static void main(String[] args) {
        // 如果不是RuntimeException则必须显示处理
        Person p = new Person();
        try {
            p.setAge(-17);
            System.out.println(p.getAge());
        } catch (Exception e) {
            System.out.println("年龄是-17");
        }

        Student s = new Student();
        s.setAge(-19);
        try {
            s.setAge(-19);
            System.out.println(s.getAge());
        } catch (RuntimeException e) {
            System.out.println("年龄是-19");
        }
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) throws Exception {
        if (age > 0 && age < 150) {
            this.age = age;
        } else {
            throw new Exception("年龄非法");

        }
    }
}

class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Student() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age > 0 && age < 150) {
            this.age = age;
        } else {
            throw new RuntimeException("年龄非法");
        }
    }
}
